
import Head from 'next/head'

<Head>
  <script>
    {
      `(function() {
         var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?e60fb290e204e04c5cb6f79b0ac1e697";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
       })();`
    }
  </script>
</Head>

![LangChain](https://pica.zhimg.com/50/v2-56e8bbb52aa271012541c1fe1ceb11a2_r.gif)






 数据增强问答
 [#](#data-augmented-question-answering "Permalink to this headline")
=========================================================================================================

>  数据增强问答 Data Augmented Question Answering


本文档使用一些通用的提示/语言模型来评估一个问答系统，该系统使用除了模型中的数据之外的其他数据源。例如，这可以用于评估问答系统对您的专有数据。


设置 Setup
 [#](#setup "Permalink to this headline")
-------------------------------------------------



让我们用我们最喜欢的例子--国情咨文来举一个例子。




```python
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_splitter import CharacterTextSplitter
from langchain.llms import OpenAI
from langchain.chains import RetrievalQA

```










```python
from langchain.document_loaders import TextLoader
loader = TextLoader('../../modules/state_of_the_union.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)

embeddings = OpenAIEmbeddings()
docsearch = Chroma.from_documents(texts, embeddings)
qa = RetrievalQA.from_llm(llm=OpenAI(), retriever=docsearch.as_retriever())

```








```python
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.

```








示例 Examples
 [#](#examples "Permalink to this headline")
-------------------------------------------------------



现在我们需要一些例子来评估。我们可以通过两种方式做到这一点：

1. 我们自己硬编码一些例子
2. 使用语言模型自动生成示例







```python
# Hard-coded examples
examples = [
    {
        "query": "What did the president say about Ketanji Brown Jackson",
        "answer": "He praised her legal ability and said he nominated her for the supreme court."
    },
    {
        "query": "What did the president say about Michael Jackson",
        "answer": "Nothing"
    }
]

```










```python
# Generated examples
from langchain.evaluation.qa import QAGenerateChain
example_gen_chain = QAGenerateChain.from_llm(OpenAI())

```










```python
new_examples = example_gen_chain.apply_and_parse([{"doc": t} for t in texts[:5]])

```










```python
new_examples

```








```python
[{'query': 'According to the document, what did Vladimir Putin miscalculate?',
  'answer': 'He miscalculated that he could roll into Ukraine and the world would roll over.'},
 {'query': 'Who is the Ukrainian Ambassador to the United States?',
  'answer': 'The Ukrainian Ambassador to the United States is here tonight.'},
 {'query': 'How many countries were part of the coalition formed to confront Putin?',
  'answer': '27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.'},
 {'query': 'What action is the U.S. Department of Justice taking to target Russian oligarchs?',
  'answer': 'The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets.'},
 {'query': 'How much direct assistance is the United States providing to Ukraine?',
  'answer': 'The United States is providing more than $1 Billion in direct assistance to Ukraine.'}]

```










```python
# Combine examples
examples += new_examples

```








 评估 Evaluate
 [#](#evaluate "Permalink to this headline")
-------------------------------------------------------


现在我们有了示例，我们可以使用问答评估器来评估我们的问答链。





```python
from langchain.evaluation.qa import QAEvalChain

```










```python
predictions = qa.apply(examples)

```










```python
llm = OpenAI(temperature=0)
eval_chain = QAEvalChain.from_llm(llm)

```










```python
graded_outputs = eval_chain.evaluate(examples, predictions)

```










```python
for i, eg in enumerate(examples):
    print(f"Example {i}:")
    print("Question: " + predictions[i]['query'])
    print("Real Answer: " + predictions[i]['answer'])
    print("Predicted Answer: " + predictions[i]['result'])
    print("Predicted Grade: " + graded_outputs[i]['text'])
    print()

```








```python
Example 0:
Question: What did the president say about Ketanji Brown Jackson
Real Answer: He praised her legal ability and said he nominated her for the supreme court.
Predicted Answer:  The president said that she is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by both Democrats and Republicans.
Predicted Grade:  CORRECT

Example 1:
Question: What did the president say about Michael Jackson
Real Answer: Nothing
Predicted Answer:  The president did not mention Michael Jackson in this speech.
Predicted Grade:  CORRECT

Example 2:
Question: According to the document, what did Vladimir Putin miscalculate?
Real Answer: He miscalculated that he could roll into Ukraine and the world would roll over.
Predicted Answer:  Putin miscalculated that the world would roll over when he rolled into Ukraine.
Predicted Grade:  CORRECT

Example 3:
Question: Who is the Ukrainian Ambassador to the United States?
Real Answer: The Ukrainian Ambassador to the United States is here tonight.
Predicted Answer:  I don't know.
Predicted Grade:  INCORRECT

Example 4:
Question: How many countries were part of the coalition formed to confront Putin?
Real Answer: 27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.
Predicted Answer:  The coalition included freedom-loving nations from Europe and the Americas to Asia and Africa, 27 members of the European Union including France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.
Predicted Grade:  INCORRECT

Example 5:
Question: What action is the U.S. Department of Justice taking to target Russian oligarchs?
Real Answer: The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets.
Predicted Answer:  The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and to find and seize their yachts, luxury apartments, and private jets.
Predicted Grade:  INCORRECT

Example 6:
Question: How much direct assistance is the United States providing to Ukraine?
Real Answer: The United States is providing more than $1 Billion in direct assistance to Ukraine.
Predicted Answer:  The United States is providing more than $1 billion in direct assistance to Ukraine.
Predicted Grade:  CORRECT

```








使用其他指标评估  Evaluate with Other Metrics
 [#](#evaluate-with-other-metrics "Permalink to this headline")
---------------------------------------------------------------------------------------------

除了使用语言模型预测答案是正确还是不正确之外，我们还可以使用其他指标来获得对答案质量的更细致入微的看法。为此，我们可以使用Critique库[Critique](https://docs.inspiredco.ai/critique/) ，它允许对生成的文本进行各种指标的简单计算。

首先，您可以从 [Inspired Cognition Dashboard](https://dashboard.inspiredco.ai) 获取API密钥并进行一些设置：


 





```python
export INSPIREDCO_API_KEY="..."
pip install inspiredco

```








```python
import inspiredco.critique
import os
critique = inspiredco.critique.Critique(api_key=os.environ['INSPIREDCO_API_KEY'])

```

然后运行以下代码来设置配置并计算[ROUGE](https://docs.inspiredco.ai/critique/metric_rouge) 、[chrf](https://docs.inspiredco.ai/critique/metric_chrf) 、[BERTScore](https://docs.inspiredco.ai/critique/metric_bert_score)和[UniEval](https://docs.inspiredco.ai/critique/metric_uni_eval)（您也可以选择其他[other metrics](https://docs.inspiredco.ai/critique/metrics) 指标）：



 







```python
metrics = {
    "rouge": {
        "metric": "rouge",
        "config": {"variety": "rouge_l"},
    },
    "chrf": {
        "metric": "chrf",
        "config": {},
    },
    "bert_score": {
        "metric": "bert_score",
        "config": {"model": "bert-base-uncased"},
    },
    "uni_eval": {
        "metric": "uni_eval",
        "config": {"task": "summarization", "evaluation_aspect": "relevance"},
    },
}

```










```python
critique_data = [
    {"target": pred['result'], "references": [pred['answer']]} for pred in predictions
]
eval_results = {
    k: critique.evaluate(dataset=critique_data, metric=v["metric"], config=v["config"])
    for k, v in metrics.items()
}

```

最后，我们可以打印出结果。我们可以看到，总体而言，当输出在语义上正确时，以及当输出与黄金标准答案紧密匹配时，得分更高。






```python
for i, eg in enumerate(examples):
    score_string = ", ".join([f"{k}={v['examples'][i]['value']:.4f}" for k, v in eval_results.items()])
    print(f"Example {i}:")
    print("Question: " + predictions[i]['query'])
    print("Real Answer: " + predictions[i]['answer'])
    print("Predicted Answer: " + predictions[i]['result'])
    print("Predicted Scores: " + score_string)
    print()

```








```python
Example 0:
Question: What did the president say about Ketanji Brown Jackson
Real Answer: He praised her legal ability and said he nominated her for the supreme court.
Predicted Answer:  The president said that she is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by both Democrats and Republicans.
Predicted Scores: rouge=0.0941, chrf=0.2001, bert_score=0.5219, uni_eval=0.9043

Example 1:
Question: What did the president say about Michael Jackson
Real Answer: Nothing
Predicted Answer:  The president did not mention Michael Jackson in this speech.
Predicted Scores: rouge=0.0000, chrf=0.1087, bert_score=0.3486, uni_eval=0.7802

Example 2:
Question: According to the document, what did Vladimir Putin miscalculate?
Real Answer: He miscalculated that he could roll into Ukraine and the world would roll over.
Predicted Answer:  Putin miscalculated that the world would roll over when he rolled into Ukraine.
Predicted Scores: rouge=0.5185, chrf=0.6955, bert_score=0.8421, uni_eval=0.9578

Example 3:
Question: Who is the Ukrainian Ambassador to the United States?
Real Answer: The Ukrainian Ambassador to the United States is here tonight.
Predicted Answer:  I don't know.
Predicted Scores: rouge=0.0000, chrf=0.0375, bert_score=0.3159, uni_eval=0.7493

Example 4:
Question: How many countries were part of the coalition formed to confront Putin?
Real Answer: 27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.
Predicted Answer:  The coalition included freedom-loving nations from Europe and the Americas to Asia and Africa, 27 members of the European Union including France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.
Predicted Scores: rouge=0.7419, chrf=0.8602, bert_score=0.8388, uni_eval=0.0669

Example 5:
Question: What action is the U.S. Department of Justice taking to target Russian oligarchs?
Real Answer: The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets.
Predicted Answer:  The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and to find and seize their yachts, luxury apartments, and private jets.
Predicted Scores: rouge=0.9412, chrf=0.8687, bert_score=0.9607, uni_eval=0.9718

Example 6:
Question: How much direct assistance is the United States providing to Ukraine?
Real Answer: The United States is providing more than $1 Billion in direct assistance to Ukraine.
Predicted Answer:  The United States is providing more than $1 billion in direct assistance to Ukraine.
Predicted Scores: rouge=1.0000, chrf=0.9483, bert_score=1.0000, uni_eval=0.9734

```








